// pages/user/page/master/achievement/achievement.js
const app = getApp();
const db = wx.cloud.database()
const _ = db.command
import * as echarts from '../../../../../ec-canvas/echarts'

function getOption(xData, data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num) {
  var option = {
    color: ['#37a2da', '#32c5e9', '#67e0e3','#d57000','#006699','#e5323e'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: (params) => {
        if (!params.length) return ''
        let s = params[0].axisValueLabel+'\n'
        for (const iterator of params) {
          // 如果是负数则反转
          let d = iterator.data < 0 ? -iterator.data : iterator.data
          s += iterator.seriesName + '：' + d + '\n'
        }
        return s
      },
      confine: true
    },
    legend: {
      data: ['推拿平均销售额', '药品平均销售额', '副业平均销售额','推拿销售数量', '药品销售数量', '副业销售数量']
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: [
      {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666',
          formatter: (value) => {
            // 负数取反 显示的就是正数了
            if (value < 0) return -value
            else return value
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'category',
        axisTick: { show: false },
        data: xData,//['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'],
        axisLine: {
          lineStyle: {
            color: '#999'
          }
        },
        axisLabel: {
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: '推拿平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data: data_tuina_sum,//[300, 270, 340, 344, 300, 320, 310],
        itemStyle: {
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }, {
        name: '推拿销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left',formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
          }
        },
        data:data_tuina_num,// [-30, -27, -34, -34, -30, -32, -31],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      },
      {
        name: '药品平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data:data_medical_sum,// [300, 270, 340, 344, 300, 320, 310],
        itemStyle: {
          // emphasis: {
          //   color: '#37a2da'
          // }
        }
      }, {
        name: '药品销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left',formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
          }
        },
        data:data_medical_num,// [-30, -27, -34, -34, -30, -32, -31],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      }, 
      {
        name: '副业平均销售额',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'right'
          }
        },
        data:data_sideline_sum,// [120, 102, 141, 174, 190, 250, 220],
        itemStyle: {
          // emphasis: {
          //   color: '#32c5e9'
          // }
        }
      },
     
     {
        name: '副业销售数量',
        type: 'bar',
        // stack: '总量',
        label: {
          normal: {
            show: true,
            position: 'left'
            ,formatter: (value) => {
              // 值都是负数的 所以需要取反一下
              return -value.data
          } 
        }
        },
        data:data_sideline_num,// [-20, -32, -21, -34, -90, -130, -110],
        itemStyle: {
          // emphasis: {
          //   color: '#67e0e3'
          // }
        }
      }
    ]
  };
  return option;
}

let chartLine

Page({

  /**
   * 页面的初始数据
   */
  data: {
      ec: {
        onInit: function (canvas, width, height){
            //初始化echarts元素，绑定到全局变量，方便更改数据
            chartLine = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            canvas.setChart(chartLine);

            //可以先不setOption，等数据加载好后赋值，
            //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
            var xData = ['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'];  // x轴数据 自己写
            var option = getOption(xData);
            chartLine.setOption(option);
        }},
        txt_explain:"----个人业绩统计图----",
        ishidden:false,
        array: ['2018','2019', '2020', '2021'],
        index: 3,
  },

  clickSearch:function(e){
      let year = e.detail.value.year
      let that = this
      console.log(year)
      var sDate=year+"/01/00"
      var eDate=year+"/12/32"

      that.getAchieve(sDate,eDate)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getAchieve:function (sdata,edata) {
    wx.showLoading({
      title: '正在统计....',
    })
     wx.cloud.callFunction({
       name: 'getAchieveList',// 要调用的云函数名称
       data: {             // 传递给云函数的event参数
         Tid:app.userDate.userInfo.userPhone,
         sDate:sdata,//"2021/01/00",
         eDate:edata//"2021/12/32"
       }
     }).then(res => {
         console.log(res.result.data)
         var xData=['一月', '二月', '三月', '四月', '五月', '六月', '七月','八月', '九月', '十月', '十一月','十二月'];
         var data_tuina_sum =[0,0,0,0,0,0,0,0,0,0,0,0] 
         var  data_medical_sum=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_sideline_sum=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_tuina_num =[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_medical_num=[0,0,0,0,0,0,0,0,0,0,0,0]
         var data_sideline_num=[0,0,0,0,0,0,0,0,0,0,0,0]
         res.result.data.forEach((item,i)=>{
             let idx = parseInt(item.date.slice(5,7))-1
             let classify = item.goodsID.slice(0,1)
             let sum = item.unitPrice*item.salenum
            //  console.log(idx,classify,item.unitPrice,item.salenum)
             if(classify=='T'){
               data_tuina_sum[idx] += sum
               data_tuina_num[idx] -= item.salenum
             }else if(classify=='M'){
               data_medical_sum[idx] += sum
               data_medical_num[idx] -= item.salenum
             }else{
               data_sideline_sum[idx] += sum
               data_sideline_num[idx] -= item.salenum
             }
         })
           data_tuina_sum.forEach((item,i)=>{
             data_tuina_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_tuina_num[i])).toFixed(2))
           })
           data_medical_sum.forEach((item,i)=>{
             data_medical_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_medical_num[i])).toFixed(2))
           })
           data_sideline_sum.forEach((item,i)=>{
             data_sideline_sum[i] = data_medical_num[i]==0?0:parseFloat(parseFloat(item/Math.abs(data_sideline_num[i])).toFixed(2))
         })
        //  console.log(data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num)
         // 方法一：
         var option = getOption(xData, data_tuina_sum, data_medical_sum,data_sideline_sum,data_tuina_num, data_medical_num,data_sideline_num);
         //var option = getOption(xData, data_cur, data_his);
         chartLine.setOption(option);
         wx.hideLoading()
     })
  },
  onLoad: function (options) {
    let that = this
    var sDate="2021/01/00"
    var eDate="2021/12/32"
    that.getAchieve(sDate,eDate)
  },
  bindPickerChange: function(e) {
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value,
      ishidden:true
    })
  },
  clickDetail:function(e){
      wx.navigateTo({
        url: './achieveDetail/achieveDetail',
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(function () {
      // 获取 chart 实例的方式
      // console.log(chart)
    }, 2000);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})